const Koa = require("koa");
const mongoose = require("mongoose");
const bodyParser = require("koa-bodyparser");
const static = require("koa-static");
const cors = require("koa2-cors");
const logger = require("koa-logger");
const path = require("path");
const User = require("./routers/User");
const Home = require("./routers/Home");
const Login = require("./routers/Login");
const Articles = require("./routers/Articles");
const Redirect = require("./routers/Redirect");
const TestData = require("./routers/TestData");
const app = new Koa();

// 连接数据库
mongoose.connect("mongodb://localhost:27017/MyBlog");
const db = mongoose.connection;
// 监听数据库连接
db.on("error", console.error.bind(console, "连接数据库失败"));
db.once("open", function () {
  console.log("连接数据库成功");
});

// 注册中间件，用添加请求头的方式处理跨域问题
// app.use(async (ctx, next) => {
//   ctx.set("Access-Control-Allow-Origin", "http://47.122.68.107"); // 允许的来源
//   ctx.set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS"); // 允许的请求方法
//   ctx.set("Access-Control-Allow-Headers", "Content-Type, Authorization"); // 允许的请求头
//   ctx.set("Access-Control-Allow-Credentials", "true"); // 允许发送 cookies

//   if (ctx.method === "OPTIONS") {
//     ctx.status = 204; // 预检请求返回 204 状态码
//   } else {
//     await next();
//   }
// });

// 注册中间件
app.use(cors());
app.use(bodyParser());
app.use(static(path.join(__dirname, "../public"), { default: "index.html" }));
app.use(logger());

// 注册路由
app.use(Home.routes()).use(Home.allowedMethods());
app.use(User.routes()).use(User.allowedMethods());
app.use(Login.routes()).use(Login.allowedMethods());
app.use(Articles.routes()).use(Articles.allowedMethods());
app.use(TestData.routes()).use(TestData.allowedMethods());
app.use(Redirect.routes()).use(Redirect.allowedMethods());

// 监听3000端口
app.listen(3000, () => {
  console.log("服务器启动成功，监听端口 3000");
});
// 监听退出信号
process.on("SIGINT", async () => {
  await mongoose.connection.close();
  process.exit(0);
});
